package com.zmzncs.lmtc.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zmzncs.lmtc.common.util.JsonUtil;
import com.zmzncs.lmtc.module.system.dao.PermissionMapper;
import com.zmzncs.lmtc.module.system.pojo.permission.Permission;
import com.zmzncs.lmtc.module.system.pojo.permission.PermissionVO;
import com.zmzncs.lmtc.module.system.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 任建波
 * @since 2019-12-24
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 递归权限
     */
    public void buildSubs(PermissionVO parent, List<PermissionVO> subs) {
        List<PermissionVO> children = subs.stream().filter(
                sub -> (sub.getPid().equals(parent.getId()))
        ).collect(Collectors.toList());
        if (children != null && children.size() > 0) {
            parent.setChildren(children);
            children.forEach(child -> buildSubs(child, subs));
        }
    }

    /**
     * 获取权限递归树
     */
    @Override
    public List<PermissionVO> getPermissionTree() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);

        List<Permission> permissionList = permissionMapper.selectList(queryWrapper);
        List<PermissionVO> permissionVOList = JsonUtil.listTransform(permissionList, PermissionVO.class);

        //根级权限
        List<PermissionVO> permissionTree = permissionVOList.stream().filter(
                permissioni -> (permissioni.getPid().equals(0L))
        ).collect(Collectors.toList());

        //递归
        permissionTree.forEach(root -> buildSubs(root, permissionVOList));

        return permissionTree;
    }

}
